﻿// *----------------------------------------------------------------
// Copyright (C) 2017 通通优品
// 版权所有。
// 
// 类名：RedisEvent.cs
// 功能描述：TongTongMall.MallWeb.Core
// 
// Create User：jym 2017/02/09
// 
// Edit User：UserName,EditTime
// Describe：Describe
// ----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TongTongMall.Dependecy;
using TongTongMall.Events.Handlers;
using TongTongMall.MallWeb.Core.Events.EventDatas;
using TongTongMall.Redis.Cache;

namespace TongTongMall.MallWeb.Core.Events
{
    /// <summary>
    /// 写入redis 领域事件
    /// todo：考虑之后的队列，统一使用领域事件去操作redis
    /// </summary>
    public class RedisEvent :
        IEventHandler<RedisParameterEventData>,
        IEventHandler<RedisContinueEventData>,
        IEventHandler<RedisRemoveEventData>
        , ITransientDependency
    {
        private readonly IRedisCache _redisCache;
        public RedisEvent(IRedisCache redisCache)
        {
            _redisCache = redisCache;
        }

        public void HandleEvent(RedisContinueEventData eventData)
        {
            if (_redisCache.Exists(eventData.Keys))
            {
                var surplusTimeSpan = _redisCache.GetExpiration(eventData.Keys);
                _redisCache.Set(eventData.Keys, eventData.Data, surplusTimeSpan);
            }
        }

        public void HandleEvent(RedisParameterEventData eventData)
        {
            _redisCache.Set(eventData.Keys, eventData.Data, eventData.Expire);
        }
        

        public void HandleEvent(RedisRemoveEventData eventData)
        {
            if (eventData.IsPattern)
            {
                _redisCache.DeletePatternKey(eventData.Keys);
            }
            else
            {
                _redisCache.Remove(eventData.Keys);
            }
        }
    }
}
